import 'dart:collection';

import 'package:flutter_admin/api/odoo/stock_materialcheck_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_picking_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/pages/odoo/material/user_list.dart';
import 'package:quiver/strings.dart';
import '../../../../generated/l10n.dart';


class TransferLibrary extends StatefulWidget {
  TransferLibrary({required this.stockQuantList});

  final List<StockQuant> stockQuantList;

  @override
  _TransferLibraryState createState() => _TransferLibraryState();
}

class _TransferLibraryState extends State<TransferLibrary> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  List<SelectOptionVO> locationIdList = [];

  String? locationDesId;
  num? userId;
  String? userName;
  List<StockQuant> stockQuantList = [];
  List<SelectOptionVO> userIdLIst = [];
  @override
  void initState() {
    super.initState();
    stockQuantList = widget.stockQuantList;
    _loadSelectVO();
  }

  _loadSelectVO() async {
    locationIdList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "stock.location",
        name: "complete_name",
        key: 'id',
        operator: "!=",
        val: int.parse(stockQuantList[0].locationId!),
        key2: "comment",
        val2: "ZZK"
    );
    setState(() {});
  }

  selectUser() async {
    formKey.currentState?.save();
    if(isBlank(locationDesId)){
      CryUtils.message("请选择目标库房");
      return ;
    }

    ResponseBodyApi res = await DynamicDataApi.getModelById(model: "stock.location",id: locationDesId);
    if(res.success!){
      showDialog(
        barrierDismissible: false,
        context: context,
        builder: (BuildContext context) => Dialog(
          child: UserList(workshopId: res.data["workshop_id"][0].toString(),),
        ),
      ).then((v) {
        if (v != null) {
          formKey.currentState!.save();
          userName = v["name"];
          userId = v["user_id"][0];
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    var rows = this.stockQuantList.map((stockQuant) {
      print(stockQuant.productorderno);
      var result = DataRow(
          cells: [
            DataCell(Text(stockQuant.productorderno ?? '--')),
            DataCell(Text(stockQuant.productCode ?? '--')),
            DataCell(Text(stockQuant.productName ?? '--')),
            DataCell(Text(stockQuant.productDes ?? '--')),
            DataCell(Text(stockQuant.batchno ?? '--')),
            DataCell(Text(stockQuant.quantity.toString())),
            DataCell(Text(stockQuant.productUomName ?? '--')),
          ]
      );
      return result;
    }).toList();
    var table = DataTable(
      columns: [
        DataColumn(
          label: Text('生产订单号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('物料编号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('物料名称'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('规格型号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('批次号'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('库存数量'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('计量单位'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      rows: rows,
    );
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          Row(
            children: [
              CryInput(
                label: '源库房',
                width: 320,
                enable: false,
                value: stockQuantList[0].locationName,
                validator: (v) {
                  return v!.isEmpty ? S.of(context).required : null;
                },
              ),
              CrySelect(
                label: '目标库房',
                width: 350,
                dataList: locationIdList,
                value: locationDesId,
                onSaved: (v) => {locationDesId = v},
                onChange: (v) async {
                  if (locationDesId != v) {
                    userId = null;
                    userName = null;
                    setState(() {});
                  }
                },
                validator: (v) {
                  return v!.isEmpty ? S.of(context).required : null;
                },
              ),
              CryInput(
                width: 200,
                label: '接收人',
                value: userName,
                onSaved: (v) {
                  userName = v;
                },
                onTap: () => selectUser(),
                validator: (v) {
                  return v!.isEmpty ? S.of(context).required : null;
                },
              ),
            ],
          ),
          SingleChildScrollView(
            scrollDirection : Axis.horizontal,
            child: table,
          )
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            List listmap = [];
            this.stockQuantList.forEach((stockQuant) {
              Map map = new HashMap();
              map['id'] = int.parse(stockQuant.productId!);
              map['num'] = stockQuant.quantity;
              listmap.add(map);
            });

            List list = [
              ['location_id', '=', int.parse(stockQuantList[0].locationId!)],
              [
                'location_dest_id',
                '=',
                int.parse(locationDesId!)
              ],
              ['user_id', '=', userId],
              ['product', listmap]
            ];
            StockMaterialcheckOdooApi.confirm(list).then((ResponseBodyApi res) {
              if (!res.success!) {
                //CryUtils.message(re s.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text('车间移库确认'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      child: result,
    );
    // return result;
  }
}
